﻿using System;
using System.Collections.Generic;
using System.Linq;
using DeviceManagement;

namespace EnumComPortsSample
{
    class ComPort
    {
        public string DevicePath { get; set; }

        public string FriendlyName { get; set; }

        public string Description { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            IEnumerable<ComPort> ports = GetComPorts();
            foreach (var port in ports)
                Console.WriteLine("{0}, Path: {1}", port.FriendlyName, port.DevicePath);

            Console.ReadKey();
        }

        private static IEnumerable<ComPort> GetComPorts()
        {
            var ports = new List<ComPort>();

            DeviceInterface deviceInterface = new DeviceInterface(DeviceInterfacesClasses.GUID_DEVINTERFACE_COMPORT);
            using (DeviceInfoSet set = DeviceInfoSet.GetPresent(deviceInterface))
            {
                foreach (DeviceInfo device in set.GetDevices())
                {
                    ComPort port = new ComPort() { FriendlyName = device.FriendlyName, Description = device.Description };

                    DeviceInterfaceData deviceInterfaceData;
                    if ((deviceInterfaceData = set.GetDeviceInterfaceData(device).FirstOrDefault()) != null)
                        port.DevicePath = deviceInterfaceData.DevicePath;
            
                    ports.Add(port);
                }
            }

            return ports.AsReadOnly();
        }
    }
}
